package com.lv.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lv.mapper.TbSpecificationMapper;
import com.lv.mapper.TbSpecificationOptionMapper;
import com.lv.pojo.TbSpecification;
import com.lv.pojo.TbSpecificationOption;
import com.lv.service.SpecService;
import com.lv.util.Page;
import com.lv.vo.SpecVO;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
@DubboService
public class SpecServiceImpl implements SpecService {

    @Resource
    public TbSpecificationMapper sm;

    @Resource
    public TbSpecificationOptionMapper om;

    @Override
    public Page<TbSpecification> getInfo(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<TbSpecification> list = sm.selectByExample(null);
        PageInfo pb = new PageInfo(list);
        return new Page(pageNum,pageSize,pb.getTotal(),pb.getList());
    }

    //增加
    @Transactional
    @Override
    public Integer addSpecAndOption(TbSpecification spec, List<TbSpecificationOption> optionList) {
        //先保存规格表,并且返回主键
        sm.insertSelective(spec);
        long id = spec.getId();
        //批量增加
        om.insertFor(optionList, id);
        return 1;
    }

    //回显

    @Override
    public SpecVO toupdate(Long id) {
        SpecVO specVO = new SpecVO();
        TbSpecification s = sm.selectByPrimaryKey(id);
        specVO.setId(s.getId());
        specVO.setSpecName(s.getSpecName());
        //查TbSpecificationOption 并放入vo类中
        List<TbSpecificationOption> list = om.selectBySpecId(id);
        specVO.setSpecOptionsList(list);
        return specVO;

    }
    @Transactional
    @Override
    public Integer update(SpecVO specVO) {
        TbSpecification t = new TbSpecification();
        t.setId(specVO.getId());
        t.setSpecName(specVO.getSpecName());
        sm.updateByPrimaryKeySelective(t);
        om.deleteBySpecId(specVO.getId());
        for (TbSpecificationOption option : specVO.getSpecOptionsList()) {
            om.insertSelective(option);
        }
        return 1;
    }

    //删除
    @Transactional
    @Override
    public Integer delBrands(List<Long> ids) {
        for (Long id : ids) {
            sm.deleteByPrimaryKey(id);
            om.deleteBySpecId(id);
        }
        return 1;
    }

    @Override
    public List<TbSpecification> selectAll() {
        return sm.selectByExample(null);
    }
}
